#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib, urllib2, cookielib
import string, os, re, time, datetime, sys

import xbmc, xbmcgui, xbmcplugin, xbmcaddon

from xml.etree import ElementTree

def listItems(url):
	xml=getURL(url)
	tree = ElementTree.XML(xml)
	items = tree.findall('Item')
	u = sys.argv[0]
	handle = int(sys.argv[1]) 
	for item in items:
		i = xbmcgui.ListItem(label=item.findtext('Name'),thumbnailImage=item.findtext('ThumbnailUrl'))
		type = item.findtext('Type')
		
		if type == 'PlayNowVideo':
			i.setInfo( type="Video", infoLabels={'title':item.findtext('Name')})
			i.setProperty('IsPlayable', 'true')
			xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(item.findtext('ContentUrl'), i)
			return
		elif type == 'Video':
			i.setInfo( type="Video", infoLabels={'title':item.findtext('Name')})
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(handle,item.findtext('ContentUrl'),i,False)
		else:
			url2 = u + '?url=' + urllib.quote_plus(item.findtext('ContentUrl'))
			xbmcplugin.addDirectoryItem(handle,url2,i,True)

	xbmcplugin.endOfDirectory(handle)

def getURL(url):
	cj = cookielib.LWPCookieJar()
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
	opener.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2;)')]
	usock=opener.open(url)
	response=usock.read()
	usock.close()
	return response

def get_params():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]

	return param


url = 'http://webtv.cdussault.net/root.ashx'

params = get_params()

try:
	url = urllib.unquote_plus(params["url"])
except:
	pass

listItems(url)